//
//  AdminPasswordView.swift
//  TLCLockDemo
//
//  Created by run on 2024/7/25.
//

import AlertToast
import Combine
import SwiftUI
import TLCLock

struct AdminPwdView: View {
    let device: LockDevice
    

    @State var password: String = ""

    var body: some View {
        
        VStack {
            Text(device.macAddress)
                .bold()
                .foregroundColor(.orange)
                .font(.headline)
                .padding(.horizontal, 20)
                .frame(maxWidth: .infinity, alignment: .center)
            
            YxrInputView("新密码", text: $password)
            
            YxrConfirmView(title: "确认") {
                modifyPwd()
            }
            
            LogView()
        }
        .yxrNavigationTitle("修改管理员密码")
        .navigationBarItems(
            trailing: Button("读取管理员密码") {
                getAdminPassword()
            }
        )
    }

    func getAdminPassword() {
        guard let lockKey = Server.getSecret(device.macAddress) else {
            showToast("没有lockKey")
            return
        }
        Task {
            showLoading()
            let result = await device.getAdminPwd(lockKey, trackId: Server.testTrackId)
            hideLoading()
            if result.isFailure {
                showToast(result.errorMessage)
                return
            }
            let pwdModel = result.value!
            self.password = pwdModel.password
        }
    }

    func modifyPwd() {
        let pwd = password
        guard pwd.count >= 6 && pwd.count <= 9 else {
            showToast("密码6~9位")
            return
        }

        guard let lockKey = Server.getSecret(device.macAddress) else {
            showToast("没有lockKey")
            return
        }

        lockTask(desc: "modify") {
            await device.modifyAdminPassword(newPassword: pwd, lockKey: lockKey, trackId: Server.testTrackId)
        }
    }
}
